package com.bjfu.gmms.servlet.mentorServlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.MentorMapper;
import com.bjfu.gmms.model.Mentor;
import com.bjfu.gmms.model.Mentor2;
import com.bjfu.gmms.model.User;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 本Servlet用于处理用户以导师身份登录后导师个人信息的具体确认
@WebServlet("/mentorDashboardServlet")
public class MentorDashboardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前session中的用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        // 防止未登录直接访问，目前不了解本项目的拦截机制
        if(user == null) {
            response.sendRedirect("index.jsp");
            return;
        }
        // 查询导师信息 静态 + 动态
        int mentorId = user.getUser_id();
        // 查询导师信息
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession("development")) {
            MentorMapper mentorMapper = sqlSession.getMapper(MentorMapper.class);
            // 获取导师的静态和动态信息
            Mentor mentor = mentorMapper.getMentorById(mentorId);
            Mentor2 mentor2 = mentorMapper.getMentor2ById(mentorId);

            if (mentor == null || mentor2 == null) {
                // 如果导师信息不存在，跳转到错误页面 -- 之后实现
                return;
            }

            // 将导师信息存入 session 或 request
            session.setAttribute("mentor", mentor);
            session.setAttribute("mentor2", mentor2);

            // 确认导师的剩余指标
            int lastQuota = mentor2.getQuota() - mentor2.getAdmissionConfirmed();
            System.out.println("导师剩余的招生指标：" + lastQuota);
            request.setAttribute("lastQuota", lastQuota);

            // 转发到导师的 Dashboard 页面
            request.getRequestDispatcher("WEB-INF/mentor_view/mentorDashboard.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }

    }
}
